import Vue from "vue";
import VueRouter from "vue-router";

Vue.use(VueRouter)

//重写push,replace方法，解决成功与失败回调未传入的情况
//保存一份原版
const orginPush =  VueRouter.prototype.push
const orginReplace = VueRouter.prototype.replace

VueRouter.prototype.push = function(location,resolve,reject){
    if(resolve && reject){
        orginPush.call(this,location,resolve,reject)
    }else{
        orginPush.call(this,location,()=>{},()=>{})
    }
}

VueRouter.prototype.replace = function(location,resolve,reject){
    if(resolve && reject){
        orginReplace.call(this,location,resolve,reject)
    }else{
        orginReplace.call(this,location,()=>{},()=>{})
    }
}

import routes from './routes'

const router = new VueRouter({
    routes,
    scrollBehavior(to, from, savedPosition) {
        // 始终滚动到顶部
        return { x:0 , y:0 }
    },
})

export default router

//引入仓库
import store from '@/store'

router.beforeEach(async (to,from,next)=>{
    let canIGetUserInfo = store.state.user.canIGetUserInfo

    if(canIGetUserInfo){
        //如果能获取到用户信息，不允许再次访问登录页面
        if(to.path == "/registerAndLogin/login"){
            next("/home")
        }else{
            next()
        }
    }else{
        //尝试获取用户信息
        try {
            await store.dispatch('getUserInfo')
            //获取用户信息成功并放行
            next()
        } catch (error) {
            //此时用户未登录
            next()
        }
    }
})